package com.xc.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.xc.base.exception.CommonException;
import com.xc.base.model.PageParams;
import com.xc.base.model.PageResult;
import com.xc.content.mapper.CourseBaseMapper;
import com.xc.content.mapper.CourseMarketMapper;
import com.xc.content.model.dto.AddCourseDto;
import com.xc.content.model.dto.CourseBaseInfoDto;
import com.xc.content.model.dto.EditCourseDto;
import com.xc.content.model.dto.PageQueryCourseParamsDto;
import com.xc.content.model.po.CourseBase;
import com.xc.content.model.po.CourseCategory;
import com.xc.content.model.po.CourseMarket;
import com.xc.content.service.CourseBaseService;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
public class CourseBaseServiceImpl extends ServiceImpl<CourseBaseMapper, CourseBase> implements CourseBaseService {
    @Autowired
    private CourseBaseMapper courseBaseMapper;
    @Autowired
    private CourseMarketMapper courseMarketMapper;

    @Override
    public PageResult<CourseBase> pageQuery(PageParams pageParams, PageQueryCourseParamsDto pageQueryCourseParamsDto) {
        if (pageParams == null) {
            pageParams = new PageQueryCourseParamsDto();
        }
        LambdaQueryWrapper<CourseBase> queryWrapper = new LambdaQueryWrapper<>();
        //查询条件
        queryWrapper.like(StringUtils.isNotEmpty(pageQueryCourseParamsDto.getCourseName()), CourseBase::getName, pageQueryCourseParamsDto.getCourseName())
                .eq(StringUtils.isNotEmpty(pageQueryCourseParamsDto.getAuditStatus()), CourseBase::getAuditStatus, pageQueryCourseParamsDto.getAuditStatus())
                .eq(StringUtils.isNotEmpty(pageQueryCourseParamsDto.getPublishStatus()), CourseBase::getStatus, pageQueryCourseParamsDto.getPublishStatus());
        Page<CourseBase> page = new Page<>(pageParams.getPageNo(), pageParams.getPageSize());
        Page<CourseBase> courseBasePage = page(page, queryWrapper);
        PageResult<CourseBase> pageResult = new PageResult<>(courseBasePage.getRecords(), courseBasePage.getTotal(), courseBasePage.getCurrent(), courseBasePage.getSize());
        return pageResult;
    }

    /**
     * @param companyId    机构id
     * @param addCourseDto
     * @return
     */
    @Transactional
    @Override
    public CourseBaseInfoDto createCourseBase(Long companyId, AddCourseDto addCourseDto) {
        //1、项课程信息表，插入信息
        CourseBase courseBase = new CourseBase();
        BeanUtils.copyProperties(addCourseDto, courseBase);
        courseBase.setCompanyId(companyId);
        courseBase.setCreateDate(LocalDateTime.now());
        //审核状态 默认未提交
        courseBase.setAuditStatus("202002");
        //发布状态，未发布
        courseBase.setStatus("203001");
        boolean res = save(courseBase);
        if (!res) {
            throw new CommonException("添加课程失败");
        }
        //2、想课程营销表插入信息
        CourseMarket courseMarket = new CourseMarket();
        //课程信息表和营销信息表是1对1的关系 而且是主键一样，
        courseMarket.setId(courseBase.getId());
        BeanUtils.copyProperties(addCourseDto, courseMarket);
        saveCourseMarket(courseMarket);
        CourseBaseInfoDto courseBaseInfoDto = queryCourseBase(courseBase.getId());
        return courseBaseInfoDto;
    }

    /**
     * 根据课程ID 查询课程详细信息
     *
     * @param courseId
     * @return
     */
    @Override
    public CourseBaseInfoDto queryCourseBase(Long courseId) {
        CourseBase courseBase = getById(courseId);
        if (courseBase == null) {
            return null;
        }
        CourseBaseInfoDto courseBaseInfoDto = new CourseBaseInfoDto();
        CourseMarket courseMarket = Db.getById(courseId, CourseMarket.class);
        //使用LambdaQueryWrapper查询
        LambdaQueryWrapper<CourseCategory> queryWrapper = new LambdaQueryWrapper(CourseCategory.class);
        queryWrapper.eq(CourseCategory::getId, courseBase.getMt());
        //两种查询其他表某个字段的方式
        //根据一级分类ID 查询分类名称
        String mtName = Db.getObj(queryWrapper, (SFunction<CourseCategory, String>) courseCategory -> courseCategory.getName());
        //根据二级分类ID 查询分类名称
        CourseCategory courseCategory = Db.getById(courseBase.getSt(), CourseCategory.class);
        String stName = courseCategory.getName();
        courseBaseInfoDto.setMtName(mtName);
        courseBaseInfoDto.setStName(stName);

        BeanUtils.copyProperties(courseBase, courseBaseInfoDto);
        if (courseMarket != null) {
            BeanUtils.copyProperties(courseMarket, courseBaseInfoDto);
        }
        return courseBaseInfoDto;

    }

    @Transactional
    @Override
    public CourseBaseInfoDto editCourseBase(EditCourseDto editCourseDto) {
        CourseBase courseBase = new CourseBase();
        BeanUtils.copyProperties(editCourseDto, courseBase);
        courseBase.setChangeDate(LocalDateTime.now());
        boolean res = saveOrUpdate(courseBase);
        if(!res){
            throw new CommonException("修改课程失败");
        }
        //2、想课程营销表插入信息
        CourseMarket courseMarket = new CourseMarket();
        //课程信息表和营销信息表是1对1的关系 而且是主键一样，
        BeanUtils.copyProperties(editCourseDto, courseMarket);
        saveCourseMarket(courseMarket);
        CourseBaseInfoDto courseBaseInfoDto = queryCourseBase(courseBase.getId());
        return courseBaseInfoDto;
    }

    @Transactional
    @Override
    public void commit(Long id) {
        //使用LambdaUpdateWrapper
        LambdaUpdateWrapper<CourseBase> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(CourseBase::getId,id);
        //审核状态设置为 已经提交
        lambdaUpdateWrapper.set(CourseBase::getAuditStatus,"202003");
        courseBaseMapper.update(null,lambdaUpdateWrapper);
    }


    /**
     * 保存营销信息
     *
     * @param courseMarket
     */

    private void saveCourseMarket(CourseMarket courseMarket) {
        String charge = courseMarket.getCharge();
        //校验参数
        if (charge.equals("201001") && (courseMarket.getPrice() == null || courseMarket.getPrice() <= 0)) {
            throw new CommonException("课程的价格不能为空，并且必须大于0");
        }
        //课程信息表和营销信息表是1对1的关系 而且是主键一样，
        boolean res = Db.saveOrUpdate(courseMarket);
        if (!res) {
            throw new CommonException("添加或修改营销信息失败");
        }

    }

}
